package com.github.xzb617.client.route.feign;

import com.github.xzb617.client.route.constant.RouteKey;
import com.github.xzb617.client.route.constant.TransferKey;
import com.github.xzb617.client.route.utils.RequestHolder;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import io.jmnarloch.spring.cloud.ribbon.api.RibbonFilterContext;
import io.jmnarloch.spring.cloud.ribbon.support.RibbonFilterContextHolder;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * Route header in Feign Interceptor
 * @author xzb617
 */
public class GoalkeeperRouteFeignInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        HttpServletRequest request = RequestHolder.currentServletRequest();
        if (request != null) {
            // headers
            Enumeration<String> headerNames = request.getHeaderNames();
            // Get ribbon context
            RibbonFilterContext ribbonCtx = RibbonFilterContextHolder.getCurrentContext();

            while (headerNames.hasMoreElements()) {
                String headerName = headerNames.nextElement();

                // need transfer headers
                if (headerName!=null && headerName.startsWith(TransferKey.HEADER_TRANSFER_PREFIX)) {
                    //substring real header name
                    String headerValue = request.getHeader(headerName);
                    requestTemplate.header(headerName, headerValue);
                }

                // Continue transfer route header to next server and ribbon context
                // route header name must starts with 'gk-route-'
                if (headerName!=null && headerName.startsWith(RouteKey.ROUTE_KEY_PREFIX)) {
                    String headerValue = request.getHeader(headerName);
                    requestTemplate.header(headerName, headerValue);
                    ribbonCtx.add(headerName, headerValue);
                }
            }

        }

    }

}
